package com.wolfalpha.utron.activity;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.fragment.RegisterIndentity;
import com.wolfalpha.utron.fragment.RegisterPhone;
import com.wolfalpha.utron.fragment.RegisterPwd;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;

/**
 * 注册
 *
 * @author luodon
 */
public class RegisterActivity extends Activity {

    private ImageView ivBack;
    private TextView tvTitle;

    private RegisterPhone f_phone;
    private RegisterIndentity f_inden;
    private RegisterPwd f_pwd;

    private String mPhone;   //电话
    private String nick;//昵称
    private String password;     //密码
    private String code;       //学校代码

    private int index = 0;

    private final static int REGISTER_START = 1;
    private final static int REGISTER_FINISH = 2;
    private final static int TEXT_CHANGE = 3;

    private ProgressDialog pd;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REGISTER_START:
                    //开始注册
                    pd = new ProgressDialog(RegisterActivity.this);
                    pd.setMessage("正在完成注册");
                    pd.show();
                    break;
                case REGISTER_FINISH:
                    //注册成功
                    UIHelper.showActivityAndFinish(RegisterActivity.this, LoginActivity.class);
                    break;
                case TEXT_CHANGE:
                    //改变标题
                    tvTitle.setText(msg.obj.toString());
                    tvTitle.invalidate();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initHead();

        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        if (savedInstanceState == null) {
            f_phone = new RegisterPhone();
            f_inden = new RegisterIndentity();
            f_pwd = new RegisterPwd();

            ft.add(R.id.register_container, f_phone, "f_phone");
            ft.add(R.id.register_container, f_inden, "f_inden");
            ft.add(R.id.register_container, f_pwd, "f_pwd");

            ft.hide(f_inden);
            ft.hide(f_pwd);

            ft.commit();
        } else {
            f_phone = (RegisterPhone) fm.findFragmentByTag("f_phone");
            f_inden = (RegisterIndentity) fm.findFragmentByTag("f_inden");
            f_pwd = (RegisterPwd) fm.findFragmentByTag("f_pwd");
        }

        initListeners();
    }

    /**
     * 初始化头部
     */
    private void initHead() {
        ivBack = (ImageView) findViewById(R.id.header_iv_back);
        tvTitle = (TextView) findViewById(R.id.header_tv_title);
        tvTitle.setText("注册-手机");
    }

    /**
     * 注册监听事件
     */
    public void initListeners() {
        f_phone.setPhoneListener(new RegisterPhone.RegisterPhoneListener() {
            @Override
            public void onFinished(String phone) {
                mPhone = phone;
                showNext(1);
            }
        });

        f_inden.setIndentityListener(new RegisterIndentity.RegisterIndentityListener() {
            @Override
            public void onFinished(String nickname, String scode) {
                nick = nickname;
                code = scode;

                showNext(2);
            }
        });

        f_pwd.setPwdListener(new RegisterPwd.RegisterPwdListener() {
                                 @Override
                                 public void onFinished(String pwd) {
                                     password = pwd;
                                     handler.sendEmptyMessage(REGISTER_START);

                                     new Thread(new Runnable() {
                                         public void run() {

                                             ThreadPoolUtils.execute(new Runnable() {
                                                                         @Override
                                                                         public void run() {
                                                                             final UserService userService = new UserServiceImpl();
                                                                             try {
                                                                                 final boolean b = userService.register(mPhone, nick, password, code);
                                                                                 runOnUiThread(new Runnable() {
                                                                                     public void run() {
                                                                                         if (b) {
                                                                                             //注册成功
                                                                                             success = true;
                                                                                             handler.sendEmptyMessage(REGISTER_FINISH);
                                                                                         } else {
                                                                                             //注册失败
                                                                                             UIHelper.ToastMessage(RegisterActivity.this, "注册失败，请重试");
                                                                                             success = false;
                                                                                         }
                                                                                     }
                                                                                 });
                                                                             } catch (Exception e) {
                                                                                 e.printStackTrace();
                                                                                 UIHelper.ToastMessage(RegisterActivity.this, "注册失败，请重试");
                                                                             }
                                                                             runOnUiThread(new Runnable() {
                                                                                 @Override
                                                                                 public void run() {
                                                                                     if (pd != null && pd.isShowing()) {
                                                                                         pd.dismiss();
                                                                                     }
                                                                                 }
                                                                             });
                                                                         }
                                                                     }

                                             );
                                         }
                                     }).start();
                                 }

                                 @Override
                                 public void onEnterMain() {
                                     if (success)
                                         UIHelper.showActivityAndFinish(RegisterActivity.this, LoginActivity.class);
                                 }
                             }

        );

        ivBack.setOnClickListener(new View.OnClickListener()

                                  {
                                      @Override
                                      public void onClick(View v) {
                                          if (index == 2) {
                                              //返回到身份信息页面
                                              showNext(1);
                                          } else if (index == 1) {
                                              showNext(0);
                                          } else if (index == 0) {
                                              UIHelper.showActivityAndFinish(RegisterActivity.this, LoginActivity.class);
                                          }
                                      }
                                  }

        );
    }


    private boolean success = false;

    /**
     * 自动翻页
     */

    private void showNext(int i) {
        i = i % 3;
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        Message msg = new Message();
        msg.what = TEXT_CHANGE;
        if (i == 0) {
            ft.hide(f_inden);
            ft.hide(f_pwd);
            ft.show(f_phone);
            msg.obj = ("注册-手机");
            index = 0;
        } else if (i == 1) {
            ft.hide(f_phone);
            ft.hide(f_pwd);
            ft.show(f_inden);
            msg.obj = ("注册-身份");
            index = 1;
        } else if (i == 2) {
            ft.hide(f_inden);
            ft.hide(f_phone);
            ft.show(f_pwd);
            msg.obj = ("注册-密码");
            index = 2;
        }
        ft.commit();
        handler.sendMessage(msg);
    }

    /**
     * 翻页
     */
    private void showTag(String tag) {
        FragmentManager fm = getFragmentManager();
        if (!fm.findFragmentByTag(tag).isVisible()) {
            fm.beginTransaction().show(fm.findFragmentByTag(tag));
            fm.beginTransaction().commit();
        }
    }

    public void onResume() {
        super.onResume();
        //友盟统计
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        //友盟统计
        MobclickAgent.onPause(this);
    }

}
